{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.coupon-box .layui-form{
		padding: 0!important;
	}

	.layui-layer-page .layui-layer-content{
		overflow: auto !important;
	}

	.del-btn {
		cursor: pointer;
	}
	.level-equity .layui-input {
		display: inline-block;
	}
	.gods-box table:first-of-type{
		margin-bottom: 0;
	}
	.gods-box table:last-of-type{
		margin-top: 0;
		display: block;
		max-height: 323px;
		overflow: auto;
	}
	.coupon-box .single-filter-box{
		padding-top: 0;
	}
	.coupon-box .select-coupon-btn{
		margin-top: 10px;
	}
	.layui-layer-page .layui-layer-content{
		overflow-y: scroll!important;
	}
	.num-name{display: inline-block}
</style>
{/block}
{block name="main"}
<div class="layui-form">

	<div class="layui-card card-common card-brief">
		<div class="layui-card-header">
			<span class="card-title">活动设置</span>
		</div>
		<div class="layui-card-body">

			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
				<div class="layui-input-block">
					<input type="text" name="recommend_name" lay-verify="required|len" class="layui-input len-long" autocomplete="off" maxlength="40">
				</div>
				<div class="word-aux">
					<p>活动名称最多为25个字符</p>
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
				<div class="layui-inline">
					<div class="layui-input-inline len-mid">
						<input type="text" class="layui-input" name="start_time" lay-verify="required" id="start_time" autocomplete="off" readonly>
						<i class=" iconrili iconfont calendar"></i>
					</div>
					<span class="layui-form-mid">-</span>
					<div class="layui-input-inline len-mid end-time">
						<input type="text" class="layui-input" name="end_time" lay-verify="required|time" id="end_time" autocomplete="off" readonly>
						<i class=" iconrili iconfont calendar"></i>
					</div>
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">活动说明：</label>
				<div class="layui-input-block">
					<textarea class="layui-textarea len-long" name="remark" maxlength="150"></textarea>
				</div>
			</div>

		</div>
	</div>

	<div class="layui-card card-common card-brief">
		<div class="layui-card-header">
			<span class="card-title">规则设置</span>
		</div>
		<div class="layui-card-body reward-wrap">
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>邀请人可得奖励：</label>
				<div class="layui-input-block">
					<input type="checkbox" name="type" value="point" title="积分" lay-skin="primary" lay-filter="type" lay-verify="type" checked>
					<input type="checkbox" name="type" value="balance" title="余额" lay-skin="primary" lay-filter="type" lay-verify="type">
					<input type="checkbox" name="type" value="coupon" title="优惠券" lay-skin="primary" lay-filter="type" lay-verify="type">
				</div>
			</div>

			<div class="point-wrap">
				<div class="layui-form-item">
					<label class="layui-form-label"><span class="required">*</span>奖励积分：</label>
					<div class="layui-input-block">
						<input name="point" value="0" type="number" lay-verify="required|mum" class="layui-input len-short">
					</div>
				</div>
			</div>

			<div class="balance-wrap layui-hide">
				<div class="layui-form-item">
					<label class="layui-form-label"><span class="required">*</span>奖励红包：</label>
					<div class="layui-input-block len-long">
						<input name="balance" value="0" type="number" lay-verify="" class="layui-input len-short">
					</div>
				</div>
				<div class="word-aux"><p>红包为储值余额，仅在消费时可用</p></div>
			</div>

			<div class="coupon-wrap layui-hide">
				<div class="layui-form-item">
					<label class="layui-form-label"><span class="required">*</span>奖励优惠券：</label>
					<div class="layui-input-block">
						<table class="layui-table" id="coupon_selected" lay-skin="line" lay-size="lg">
							<colgroup>
								<col width="35%">
								<col width="25%">
								<col width="20%">
								<col width="20%">
							</colgroup>
							<thead>
								<tr>
									<th>优惠券名称</th>
									<th>优惠金额/折扣</th>
									<th>有效期</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td class="goods-empty" colspan="4">
										<div>尚未选择赠送优惠券</div>
									</td>
								</tr>
							</tbody>
						</table>
						<div class="word-aux text-color" style="margin-left: 0">
							<p>活动优惠券发放，不受优惠券自身数量和领取数量的限制</p>
						</div>
						<button class="layui-btn" onclick="addCoupon()">添加优惠券</button>
					</div>
				</div>
			</div>

			<div class="max-fetch-wrap">
				<div class="layui-form-item">
					<label class="layui-form-label"><span class="required">*</span>邀请奖励上限：</label>
					<div class="layui-input-block">
						<input name="max_fetch" value="0" type="number" class="layui-input len-short num-name">
						人
						<div class="word-aux text-color" style="margin-left: 0">
							<p>默认0，为不限制</p>
						</div>
					</div>
				</div>
			</div>

			<div class="form-row">
				<button class="layui-btn" lay-submit lay-filter="save">保存</button>
				<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
			</div>

		</div>
	</div>
</div>

{/block}
{block name="script"}
<script>
    var coupon_id = [], addCoupon,
        currentDate = new Date();  //当前时间;

    layui.use(['form', 'laytpl', 'laydate'], function() {
        var form = layui.form,
            laytpl = layui.laytpl,
            laydate = layui.laydate,
            repeat_flag = false; //防重复标识
        form.render();

        currentDate.setDate(currentDate.getDate() + 30);   //当前时间+30之后的时间戳

        // 开始时间
        laydate.render({
            elem: '#start_time' ,//指定元素
            type: 'datetime',
            value: new Date(),
            done: function(value){
                minDate = value;
                reRender();
            }
        });

        //结束时间
        laydate.render({
            elem: '#end_time' ,//指定元素
            type: 'datetime',
            value: new Date(currentDate)
        });

        /**
         * 重新渲染结束时间
         * */
        function reRender(){
            $("#end_time").remove();
            $(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class="layui-input len-mid" autocomplete="off"><i class=" iconrili iconfont calendar"></i>');
            laydate.render({
                elem: '#end_time',
                type: 'datetime',
                min: minDate
            });
        }

        form.on('checkbox(type)', function(data) {
            $('[name="type"]').each(function(){
                var type = $(this).val();
                if ($(this).is(':checked')) {
                    $('.reward-wrap .' + type + '-wrap').removeClass('layui-hide');
                    if (type == 'point' || type == 'coupon') {
                        $('.reward-wrap .' + type + '-wrap [lay-verify]').attr('lay-verify', 'required|mum');
                    }
                    if (type == 'balance') {
                        $('.reward-wrap .' + type + '-wrap [lay-verify]').attr('lay-verify', 'required|float');
                    }
                } else {
                    $('.reward-wrap .' + type + '-wrap').addClass('layui-hide');
                    $('.reward-wrap .' + type + '-wrap [lay-verify]').attr('lay-verify', '');
                }
            })
        })

        /**
         * 监听保存
         */
        form.on('submit(save)', function(data) {
            var type = [];
            $('.reward-wrap [name="type"]:checked').each(function(){
                type.push($(this).val());
            })
            if ($.inArray('coupon', type) != -1 && coupon_id.length == 0) {
                layer.msg('请选择优惠券', {icon: 5});
                return;
            }

			if(data.field.max_fetch == ''){
				layer.msg('请输入邀请奖励上限', {icon: 5});
				return;
			}else if (data.field.max_fetch < 0){
				layer.msg('请输入大于或等于0的整数', {icon: 5});
				return;
			}

            data.field.type = type.toString();
            data.field.coupon = coupon_id.toString();

            if (repeat_flag) return false;
            repeat_flag = true;

            $.ajax({
                url: ns.url("memberrecommend://shop/memberrecommend/add"),
                data: data.field,
                dataType: 'JSON', //服务器返回json格式数据
                type: 'POST', //http请求类型
                success: function(res) {
                    repeat_flag = false;
                    if (res.code == 0) {
                        layer.confirm('添加成功', {
                            title:'操作提示',
                            btn: ['返回列表', '继续添加'],
                            closeBtn: 0,
                            yes: function(){
                                location.href = ns.url("memberrecommend://shop/memberrecommend/lists")
                            },
                            btn2: function() {
                                location.href = ns.url("memberrecommend://shop/memberrecommend/add")
                            }
                        });
                    }else{
                        layer.msg(res.message);
                    }
                }
            });
        });

        /**
         * 表单验证
         */
        form.verify({
            type: function(){
                if ($('.reward-wrap [name="type"]:checked').length == 0) {
                    return '请选择邀请人可得奖励';
                }
            },
            mum: function(value, item){
                if (/^\d{0,10}$/.test(value) === false) {
                    return '请输入大于0的整数';
                }

                if (parseInt(value) <= 0) {
                    return '请输入大于0的整数';
                }
            },
            float: function(value, item){
                if (/^\d{0,10}$/.test(value) === false) {
                    return '请输入大于0的数字，支持小数点后两位';
                }
                if (parseInt(value) <= 0) {
                    return '请输入大于0的数字，支持小数点后两位';
                }
            }
        });

        //优惠券
        addCoupon = function() {
            var data = {};
            data.coupon_id = coupon_id;

            laytpl($("#couponList").html()).render(data, function(html) {
                coupon_list = layer.open({
                    title: '优惠券列表',
                    skin: 'layer-tips-class',
                    type: 1,
                    area: ['1100px', '600px'],
                    content: html,
                });

                if ($("tbody tr input:checked").length == $(".coupon-box tbody tr").length) {
                    $("input[lay-filter='selectAll']").prop("checked", true);
                }

                form.render();
            });

            /**
             * 监听全选按钮
             */
            form.on('checkbox(selectAll)', function(data) {
                if (data.elem.checked) {
                    $("tr .check-box input:checkbox").each(function(index) {
                        $(this).prop("checked", true);
                    });
                } else {
                    $("tr .check-box input:checkbox").each(function() {
                        $(this).prop("checked", false);
                    });
                }
                form.render();
            });

            /**
             * 监听每一行的多选按钮
             */
            var len = $(".coupon-box tbody tr").length;
            for (var i = 0; i < len; i++) {
                form.on('checkbox(select' + i + ')', function(data) {
                    if ($("tbody tr input:checked").length == len) {
                        $("input[lay-filter='selectAll']").prop("checked", true);
                    } else {
                        $("input[lay-filter='selectAll']").prop("checked", false);
                    }

                    form.render();
                });
            }
        }
    });

    function couponSelected() {
        layer.closeAll('page');

        coupon_id = [];
        var _len = $("tbody tr input:checked").length;

        $("#coupon_selected tbody").empty();

        $("#coupon tbody tr").each(function(){
            var bool = $(this).find("input[type='checkbox']").is(":checked");

            if (bool) {
                coupon_id.push($(this).find("#coupon_id").val());
                var html = '';

                var _id = $(this).find("#coupon_id").val(),
                    image = $(this).find(".title-pic img").attr("src"),
                    coupon_name = $(this).find(".title-content p").text(),
                    money = $(this).find(".coupon-money").text(),
                    stock = $(this).find(".coupon-stock").text(),
                    end_time = $(this).find(".coupon-end-time").text();

                html += '<tr>'+
                    '<td>'+
                    '<div class="table-title">'+
                    '<input type="hidden" value="'+ _id +'" />'+
                    '<div class="title-pic">';
                if (image) {
                    html +=   			'<img src="'+ image +'">';
                }
                html +=				'</div>'+
                    '<div class="title-content">'+
                    '<p class="multi-line-hiding">'+ coupon_name +'</p>'+
                    '</div>'+
                    '</div>'+
                    '</td>'+
                    '<td class="layui-elip coupon-money">'+ money +'</td>'+
                    '<td class="layui-elip coupon-end-time">'+ end_time +'</td>'+
                    '<td class="layui-elip"><div class="table-btn"><a class="layui-btn del-btn" onclick="delCoupon(this)">删除</a></div></td>'+
                    '</tr>';

                $("#coupon_selected tbody").append(html);
            }
        });

		if (_len == 0) {
			var html = '<tr>'+
				'<td class="goods-empty" colspan="4">'+
				'<div>尚未选择赠送优惠券</div>'+
				'</td>'+
				'</tr>';
			$("#coupon_selected tbody").append(html);
		}
    }

    //删除优惠券
    function delCoupon(e) {
        $(e).parents("tr").remove();

        var _len = $("#coupon_selected tbody tr").length;
        if(_len == 0) {
            var html = '<tr>'+
                '<td class="goods-empty" colspan="4">'+
                '<div>尚未选择赠送优惠券</div>'+
                '</td>'+
                '</tr>';
            $("#coupon_selected tbody").append(html);
        }

        couponId();
    }

    function couponId() {
        coupon_id = [];

        $("#coupon_selected tbody tr").each(function(){
            coupon_id.push($(this).find(".table-title input").val());
        });
    }

    function back(){
        location.href = ns.url("memberrecommend://shop/memberrecommend/lists");
    }
</script>

<!-- 优惠券 -->
<script type="text/html" id="couponList">
	<div class="coupon-box">
		<!--<div class="single-filter-box">-->
			<!--<div class="layui-form">-->
				<!--<div class="layui-input-inline">-->
					<!--<input type="text" name="coupon_name" placeholder="请输入优惠券名称" class="layui-input">-->
					<!--<button type="button" class="layui-btn layui-btn-primary" lay-filter="coupon-search" lay-submit>-->
						<!--<i class="layui-icon">&#xe615;</i>-->
					<!--</button>-->
				<!--</div>-->
			<!--</div>-->
		<!--</div>-->
		<div>
			<table class="layui-table" lay-skin="line" id="coupon">
				<colgroup>
					<col width="10%">
					<col width="20%">
					<col width="10%">
					<col width="10%">
					<col width="10%">
					<col width="20%">
					<col width="20%">
				</colgroup>
				<thead>
					<tr>
						<th class="check-box">
							<div class="layui-form">
								<input type="checkbox" name="" lay-filter="selectAll" lay-skin="primary">
							</div>
						</th>
						<th class="layui-elip">优惠券名称</th>
						<th class="layui-elip">类型</th>
						<th class="layui-elip">优惠金额/折扣</th>
						<th class="layui-elip">适用商品</th>
						<th class="layui-elip">领取人限制</th>
						<th class="layui-elip">已领取/发放数</th>
						<th class="layui-elip">结束时间</th>
					</tr>
				</thead>
				<tbody>
					{foreach $coupon_list.data as $coupon_list_k => $coupon_list_v}
					<tr>
						<td class="check-box">
							<div class="layui-form">
								{{# var a = {$coupon_list_v.coupon_type_id} }}
								{{#  if($.inArray(a.toString(), d.coupon_id) != -1){  }}
								<input type="checkbox" name="" lay-filter="select{$coupon_list_k}" lay-skin="primary" checked>
								{{#  }else{  }}
								<input type="checkbox" name="" lay-filter="select{$coupon_list_k}" lay-skin="primary">
								{{#  }  }}
								<input type="hidden" id="coupon_id" value="{$coupon_list_v.coupon_type_id}">
							</div>
						</td>
						<td>
							<div class="table-title">
								<div class="title-pic">
									{if condition="$coupon_list_v.image"}
									<img src="{:img($coupon_list_v.image)}">
									{else/}
									<img src="__ROOT__/public/uniapp/game/coupon.png">
									{/if}
								</div>
								<div class="title-content">
									<p class="multi-line-hiding">{$coupon_list_v.coupon_name}</p>
								</div>
							</div>
						</td>

						{if $coupon_list_v.type == 'reward'}
						<td class="layui-elip">满减</td>
						{else/}
						<td class="layui-elip">折扣</td>
						{/if}

						{if $coupon_list_v.type == 'reward'}
						<td class="layui-elip coupon-money">{$coupon_list_v.money}元</td>
						{else/}
						<td class="layui-elip coupon-money">{$coupon_list_v.discount}折</td>
						{/if}

						{if $coupon_list_v.goods_type == 1}
						<td width="101px" class="layui-elip">全部商品</td>
						{elseif $coupon_list_v.goods_type == 2}
						<td width="101px" class="layui-elip">指定商品</td>
						{elseif $coupon_list_v.goods_type == 3}
						<td width="101px" class="layui-elip">指定不参与商品</td>
						{/if}

						<td class="layui-elip">{$coupon_list_v.max_fetch}</td>

						{if $coupon_list_v.count == -1}
						<td class="layui-elip coupon-stock">{$coupon_list_v.lead_count}/不限量</td>
						{else/}
						<td class="layui-elip coupon-stock">{$coupon_list_v.lead_count}/{$coupon_list_v.count}</td>
						{/if}

						{if $coupon_list_v.validity_type == 0}
						<td class="layui-elip coupon-end-time">{:time_to_date($coupon_list_v.end_time)}</td>
						{elseif $coupon_list_v.validity_type == 1}
						<td class="layui-elip coupon-end-time">领取之日起{$coupon_list_v.fixed_term}天有效</td>
						{else/}
						<td class="layui-elip coupon-end-time">长期有效</td>
						{/if}
					</tr>
					{/foreach}
				</tbody>
			</table>
			<button class="layui-btn select-coupon-btn" onclick="couponSelected()">确定</button>
		</div>
	</div>
</script>
{/block}